import React, { useEffect, useState } from 'react';
import Form from '@knownsec/react-component/dist/Form';
import Label from '../../../components/Label';
import Helper from '../../../components/Helper';
import Icon from '@knownsec/react-component/dist/Icon';
import Input from '@knownsec/react-component/dist/Input';
import Button from '@knownsec/react-component/dist/Button';
import InputNumber from '@knownsec/react-component/dist/InputNumber';
import Switch from '@knownsec/react-component/dist/Switch';
import Select from '@knownsec/react-component/dist/Select';
import Checkbox from '@knownsec/react-component/dist/Checkbox';
import Textarea from '@knownsec/react-component/dist/Textarea';
import Message from '@knownsec/react-component/dist/Message';
import Radio from '@knownsec/react-component/dist/Radio';
import s from '../style.module.css';
import cn from 'classnames';
import recursion from '../../../helpers/recursionFormJob';
import { name } from '../../../../../package.json';
import {
	SSL_CATEGORY_KEY_LABEL_MAP,
	CONTENT_KEYWORD_TYPES,
	CONTENT_PRIVACY_DISCLOSURE_TYPES,
	FREQ_UNIT_MAP,
	NODE_ID_LABEL_MAP2,
	FREQUENCY_NUMBERS,
	WEAKNESS_FREQUENCY_UNIT_MAP,
	FREQUENCY_UNIT_MAP,
} from '../../../../common/constants';
import fetchFer from 'API/fetch';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import {
	getMaxDepthOptions,
	getMaxPageOptions,
	getChangeBaseOptions,
} from './unit';

const SECURITY_EVENT_TYPE_MAP = {
	black_links: '暗链',
	broken_links: '坏链',
	cryjack: '挖矿',
	malscan: '挂马',
	foreign_links_2: '风险外链(违规内容)',
	foreign_links_3: '风险外链(风险域名)',
	foreign_links_1: '风险外链(未备案)',
};

const notEnableTip = () => {
	return (
		<span className={cn(s.warningColor, s.ml10, s.fwn)}>
			未启用该监测项，暂不支持配置。
		</span>
	);
};

function VulSettings({
	data,
	enable,
	triggerType,
	type,
	vulnsTemp,
	cydEnabled = false,
}) {
	const form = Form.useFormInstance();
	const VUL_SETTING_OPTIONS = window.kuiper?.app?.config[name].settingOptions;
	const [itemControl, setItemControl] = useState(enable ? 'down' : 'up');
	const vulContentType =
		Form.useWatch(['vul_settings', 'collect', 'type'], form) ||
		data?.vul_settings?.collect?.type;
	const vulType =
		Form.useWatch(['vul_settings', 'vulType'], form) ||
		data?.vul_settings?.vulType;
	const [vulnsList, setVulnsList] = useState([]);
	const getVulnsList = async () => {
		const res = await fetchFer(`/api/v2/vulndb/kb_vulns`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		const mapData = {};
		const data = res.data.map(item => {
			mapData[item.source_id] = item.name.zh_cn;
			return { label: item.name.zh_cn, value: item.source_id };
		});
		setVulnsList(data);
	};
	const validatormap = (rule, value) => {
		// message: '请选择监测资产'
		if (type === '上一步') {
			return Promise.resolve();
		}
		if (rule.field === 'vul_settings.collect.vul' && !value[0]) {
			return Promise.reject('请选择漏洞模板');
		}
		if (rule.field === 'vul_settings.collect.vulns' && !value[0]) {
			return Promise.reject('请选择漏洞插件');
		}
		return Promise.resolve();
	};
	const checkCount = async () => {
		const res = await fetchFer(`/api/v2/kb/custom_profile_count`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		if (res.msg === 'ok') {
			if (res.data.custom_profile_count >= 100) {
				Message.show({
					type: 'warning',
					message: '系统最多可添加100条漏洞检测模板。',
				});
			} else {
				window.open('/#/policy-manage/vul-template-settings/create');
			}
		}
	};
	useEffect(() => {
		getVulnsList();
	}, []);
	return (
		<Form
			form={form}
			className={s.settingsItem}
			initialValues={data}
			labelAlign="right"
			labelCol={{ span: 3 }}
			name="vulSettings"
			onValuesChange={(newItem, allValues) => {
				const val = recursion(newItem);
				form.setFieldsValue(val);
			}}
			wrapperCol={{ span: 20, offset: 1 }}
		>
			<div
				className={cn(s.bdb, s.pb10, s.df, s.jcsb, s.aic, 'cp')}
				onClick={() => {
					setItemControl(itemControl === 'up' ? 'down' : 'up');
				}}
			>
				<div>
					<Label className={cn(s.label, s.dib, s.vam)}>
						Web漏洞监测
						{!enable && notEnableTip()}
					</Label>
				</div>
				<Icon type={itemControl} className={cn(s.fs14, s.cp)} />
			</div>
			<div className={cn(s.m20_0, s.w876, s['content-' + itemControl])}>
				<div style={{ display: triggerType === 'schedule' ? 'block' : 'none' }}>
					<Form.Item
						label="监测方式"
						labelCol={{ span: 2 }}
						labelAlign="left"
						wrapperCol={{ span: 22 }}
						name={['vul_settings', 'collect', 'type']}
					>
						<Radio.Group>
							<Radio
								disabled={!enable}
								value="increment"
								className={cn(s.h24, s.vam)}
							>
								增量监测
							</Radio>
							<Radio
								disabled={!enable}
								className={cn(s.h24, s.vam)}
								value="full"
							>
								全量监测
							</Radio>
						</Radio.Group>
					</Form.Item>
				</div>
				<div style={{ display: triggerType === 'schedule' ? 'none' : 'block' }}>
					<Form.Item
						label="监测内容"
						labelCol={{ span: 2 }}
						labelAlign="left"
						wrapperCol={{ span: 22 }}
						name={['vul_settings', 'vulType']}
					>
						<Radio.Group>
							<Radio value="type" className={cn(s.h24, s.vam)}>
								漏洞类型
							</Radio>
							<Radio className={cn(s.ml24, s.vam, s.h24)} value="plugIn">
								漏洞插件
							</Radio>
						</Radio.Group>
					</Form.Item>
				</div>
				<div className={cn(s.mt_20, 'pr')}>
					<Form.Item
						label={triggerType === 'schedule' ? '监测内容' : ''}
						rules={[{ validator: validatormap }]}
						labelAlign="left"
						labelCol={{ span: 2 }}
						wrapperCol={{
							span: 22,
							offset: triggerType === 'schedule' ? 0 : 2,
						}}
						name={[
							'vul_settings',
							'collect',
							vulType === 'plugIn' ? 'vulns' : 'vul',
						]}
					>
						<Select
							disabled={!enable}
							className={cn(s.w100p)}
							multiple
							clearable
							searchable
							checkAll
							placeholder={
								vulType === 'plugIn' ? '请选择漏洞插件' : '请选择漏洞模板'
							}
							option={vulType === 'plugIn' ? vulnsList : vulnsTemp}
						/>
					</Form.Item>
					{vulType !== 'plugIn' && (
						<span
							className="p0 pa main-color cp"
							style={{ right: '-70px', top: '5px' }}
							onClick={() => checkCount()}
						>
							新增模板
						</span>
					)}
				</div>
				<div
					className={cn(s.flex1, s.pr)}
					style={{
						display:
							triggerType === 'schedule' && vulContentType === 'increment'
								? 'block'
								: 'none',
					}}
				>
					<Form.Item
						label={
							<div className="df aic">
								网站画像监测引擎
								<Helper
									className={cn('ml5 cp')}
									placement="top"
									overlay={
										<div className={s.maxW300}>
											启用后，平台将获取云防御日志进行分析聚合，按智能频率进行Web漏洞监测，不受自定义监测频率限制。
										</div>
									}
								/>
							</div>
						}
						labelAlign="left"
						labelCol={{ span: 5 }}
						wrapperCol={{ span: 4 }}
						name={['vul_settings', 'enableSitePortraitTriggerMonitor']}
					>
						{cydEnabled ? (
							<Switch
								disabled={!enable}
								checkedValue={true}
								unCheckedValue={false}
								style={{ marginLeft: '-32px' }}
							/>
						) : (
							<Tooltip
								placement="top"
								overlay={
									<div className={s.maxW300}>
										当前资产未接入知道创宇云防御，不支持网站画像功能
									</div>
								}
							>
								<Switch
									disabled
									value={false}
									checkedValue={true}
									unCheckedValue={false}
									style={{ marginLeft: '-32px' }}
								/>
							</Tooltip>
						)}
					</Form.Item>
				</div>
				<div
					className={cn(s.df, s.aic, s.w700)}
					style={{
						display:
							triggerType === 'schedule' && vulContentType === 'increment'
								? 'none'
								: 'flex',
					}}
				>
					<div
						className={cn(s.w260, s.pr, s.pr40)}
						style={{
							display:
								vulType === 'all' && vulContentType === 'full'
									? 'block'
									: 'none',
						}}
					>
						<Form.Item
							label="监测模式"
							labelAlign="left"
							labelCol={{ span: 8 }}
							wrapperCol={{ span: 16 }}
							name={['vul_settings', 'collect', 'speed']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2)}
								option={VUL_SETTING_OPTIONS.vulPattern.map(
									({ label, value }) => {
										return { label: label.toString(), value };
									}
								)}
							/>
						</Form.Item>
					</div>
					<div
						className={cn(
							{ [s.flex1]: vulContentType === 'full' && vulType === 'all' },
							s.pr
						)}
						style={
							vulContentType === 'full' && vulType === 'all'
								? {}
								: { width: '220px' }
						}
					>
						<Form.Item
							label="监测深度"
							labelAlign="left"
							labelCol={{
								span: 8,
								offset: vulContentType === 'full' && vulType === 'all' ? 1 : 0,
							}}
							wrapperCol={{ span: 10 }}
							name={['vul_settings', 'collect', 'depth']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2)}
								option={getMaxDepthOptions('vul')}
							/>
						</Form.Item>
					</div>
					<div
						className={cn(
							{ [s.flex1]: vulContentType === 'full' && vulType === 'all' },
							s.pr
						)}
						style={
							vulContentType === 'full' && vulType === 'all'
								? {}
								: { width: '260px' }
						}
					>
						<Form.Item
							label="监测最大URL数"
							labelAlign="left"
							labelCol={{ span: 12, offset: 1 }}
							wrapperCol={{ span: 11 }}
							name={['vul_settings', 'collect', 'maxPage']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2)}
								option={getMaxPageOptions('vul')}
							/>
						</Form.Item>
					</div>
				</div>
			</div>
		</Form>
	);
}

function SslSettings({ data, enable, triggerType, type }) {
	const form = Form.useFormInstance();
	const [itemControl, setItemControl] = useState(enable ? 'down' : 'up');
	const sslType =
		Form.useWatch(['ssl_settings', 'sslType'], form) ||
		data?.ssl_settings?.sslType;
	const validatormap = (rule, value) => {
		if (type === '上一步') {
			return Promise.resolve();
		}
		if (rule.field === 'ssl_settings.collect.pluginCategories' && !value[0]) {
			return Promise.reject('请选择SSL安全类型');
		}
		return Promise.resolve();
	};
	return (
		<Form
			form={form}
			className={s.settingsItem}
			initialValues={data}
			labelAlign="right"
			labelCol={{ span: 3 }}
			name="sslSettings"
			onValuesChange={(newItem, allValues) => {
				const val = recursion(newItem);
				form.setFieldsValue(val);
				if (val?.ssl_settings?.sslType === 'all')
					form.setFieldsValue({
						ssl_settings: {
							collect: {
								pluginCategories: Object.keys(SSL_CATEGORY_KEY_LABEL_MAP),
							},
						},
					});
			}}
			wrapperCol={{ span: 20, offset: 1 }}
		>
			<div
				className={cn(s.bdb, s.pb10, s.df, s.jcsb, s.aic, 'cp')}
				onClick={() => {
					setItemControl(itemControl === 'up' ? 'down' : 'up');
				}}
			>
				<div>
					<Label className={cn(s.label, s.dib, s.vam)}>
						SSL安全监测
						{!enable && notEnableTip()}
					</Label>
				</div>
				<Icon type={itemControl} className={cn(s.fs14, s.cp)} />
			</div>
			<div className={cn(s.m20_0, s.w876, s['content-' + itemControl])}>
				<Form.Item
					label="监测内容"
					labelAlign="left"
					labelCol={{ span: 2 }}
					rules={[{ validator: validatormap }]}
					wrapperCol={{ span: 22 }}
					name={['ssl_settings', 'collect', 'pluginCategories']}
				>
					<Select
						className={s.w100p}
						multiple
						clearable
						searchable
						checkAll
						disabled={!enable}
						placeholder="请选择SSL安全类型"
						option={Object.entries(SSL_CATEGORY_KEY_LABEL_MAP).map(
							([value, label]) => {
								return { label, value };
							}
						)}
					/>
				</Form.Item>
			</div>
		</Form>
	);
}

function SecuritySettings({ data, enable, triggerType, type }) {
	const form = Form.useFormInstance();
	const [itemControl, setItemControl] = useState(enable ? 'down' : 'up');
	const validatormap = (rule, value) => {
		if (type === '上一步') {
			return Promise.resolve();
		}
		if (rule.field === 'security_event_settings.collect.plugins' && !value[0]) {
			return Promise.reject('请选择安全事件类型');
		}
		return Promise.resolve();
	};
	return (
		<Form
			form={form}
			className={s.settingsItem}
			initialValues={data}
			labelAlign="right"
			labelCol={{ span: 3 }}
			name="securityEventSettings"
			onValuesChange={(newItem, allValues) => {
				const val = recursion(newItem);
				form.setFieldsValue(val);
			}}
			wrapperCol={{ span: 20, offset: 1 }}
		>
			<div
				className={cn(s.bdb, s.pb10, s.df, s.jcsb, s.aic, 'cp')}
				onClick={() => {
					setItemControl(itemControl === 'up' ? 'down' : 'up');
				}}
			>
				<div>
					<Label className={cn(s.label, s.dib, s.vam)}>
						安全事件监测
						{!enable ? (
							notEnableTip()
						) : (
							<span className={cn('primary-color', s.ml10, s.fwn)}>
								发现业务系统被植入暗链、坏链、挖矿、挂马、风险外链等篡改事件。
							</span>
						)}
					</Label>
				</div>
				<Icon type={itemControl} className={cn(s.fs14, s.cp)} />
			</div>
			<div className={cn(s.m20_0, s.w876, s['content-' + itemControl])}>
				<Form.Item
					label="监测内容"
					labelAlign="left"
					labelCol={{ span: 2 }}
					rules={[{ validator: validatormap }]}
					wrapperCol={{ span: 22 }}
					name={['security_event_settings', 'collect', 'plugins']}
				>
					<Select
						className={s.w100p}
						multiple
						clearable
						searchable
						checkAll
						disabled={!enable}
						placeholder="请选择安全事件类型"
						option={Object.entries(SECURITY_EVENT_TYPE_MAP).map(
							([value, label]) => {
								return { label, value };
							}
						)}
					/>
				</Form.Item>
				<div className={cn(s.df, s.aic, s.w450)}>
					<div className={cn(s.flex1, s.pr)}>
						<Form.Item
							label="监测深度"
							labelAlign="left"
							labelCol={{ span: 8 }}
							wrapperCol={{ span: 10 }}
							name={['security_event_settings', 'collect', 'depth']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2, s.ml_2)}
								option={getMaxDepthOptions('securityEvent')}
							/>
						</Form.Item>
					</div>
					<div className={cn(s.flex1, s.pr)}>
						<Form.Item
							label="监测最大URL数"
							labelAlign="left"
							labelCol={{ span: 12 }}
							wrapperCol={{ span: 11 }}
							name={['security_event_settings', 'collect', 'maxPage']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2)}
								option={getMaxPageOptions('securityEvent')}
							/>
						</Form.Item>
					</div>
				</div>
			</div>
		</Form>
	);
}

function ContentSettings({ data, enable, triggerType, type }) {
	const form = Form.useFormInstance();
	const [itemControl, setItemControl] = useState(enable ? 'down' : 'up');
	const contentType =
		Form.useWatch(['content_settings', 'type'], form) ||
		data?.content_settings?.type;
	const keyword =
		Form.useWatch(
			['content_settings', 'collect', 'systemKeywordStatus'],
			form
		) || data?.content_settings?.collect?.systemKeywordStatus;
	const privacy =
		Form.useWatch(
			['content_settings', 'collect', 'privacyDisclosureStatus'],
			form
		) || data?.content_settings?.collect?.privacyDisclosureStatus;
	const validatormap = (rule, value) => {
		if (type === '上一步') {
			return Promise.resolve();
		}
		if (
			rule.field === 'content_settings.collect.systemKeywordTypes' &&
			!value[0] &&
			keyword
		) {
			return Promise.reject('请选择敏感词类型');
		}
		if (
			rule.field === 'content_settings.collect.privacyDisclosureTypes' &&
			!value[0] &&
			privacy
		) {
			return Promise.reject('请选择隐私信息类型');
		}
		if (rule.field === 'content_settings.collect.includeUrl' && !value) {
			return Promise.reject('请输入监测URL关键参数');
		}
		return Promise.resolve();
	};
	return (
		<Form
			form={form}
			className={s.settingsItem}
			initialValues={data}
			labelAlign="right"
			labelCol={{ span: 3 }}
			name="contentSettings"
			onValuesChange={(newItem, allValues) => {
				const val = recursion(newItem);
				form.setFieldsValue(val);
				if (val?.content_settings?.collect?.systemKeywordStatus)
					form.setFieldsValue({
						content_settings: {
							collect: {
								systemKeywordTypes: CONTENT_KEYWORD_TYPES.reduce((t, i) => {
									t.push(i.idx);
									return t;
								}, []),
							},
						},
					});
				if (val?.content_settings?.collect?.privacyDisclosureStatus)
					form.setFieldsValue({
						content_settings: {
							collect: {
								privacyDisclosureTypes: CONTENT_PRIVACY_DISCLOSURE_TYPES.reduce(
									(t, i) => {
										t.push(i.idx);
										return t;
									},
									[]
								),
							},
						},
					});
			}}
			wrapperCol={{ span: 20, offset: 1 }}
		>
			<div
				className={cn(s.bdb, s.pb10, s.df, s.jcsb, s.aic, 'cp')}
				onClick={() => {
					setItemControl(itemControl === 'up' ? 'down' : 'up');
				}}
			>
				<div>
					<Label className={cn(s.label, s.dib, s.vam)}>
						内容违规监测
						{!enable ? (
							notEnableTip()
						) : (
							<span className={cn('primary-color', s.ml10, s.fwn)}>
								发现业务系统内容被恶意篡改，隐私信息泄露等违规事件。
							</span>
						)}
					</Label>
				</div>
				<Icon type={itemControl} className={cn(s.fs14, s.cp)} />
			</div>
			<div className={cn(s.m20_0, s.w876, s['content-' + itemControl])}>
				<Form.Item
					label="监测方式"
					labelCol={{ span: 2 }}
					labelAlign="left"
					wrapperCol={{ span: 22 }}
					name={['content_settings', 'type']}
				>
					<Radio.Group>
						<Radio disabled={!enable} value="full" className={cn(s.vam, s.h24)}>
							全量监测
						</Radio>
						<Radio
							disabled={!enable}
							className={cn(s.vam, s.h24)}
							value="assign"
						>
							指定页面监测
						</Radio>
					</Radio.Group>
				</Form.Item>
				<div className={cn(s.df, s.aifs)}>
					<div style={{ width: '170px' }}>
						<Form.Item
							label="监测内容"
							labelAlign="left"
							labelCol={{ span: 10 }}
							wrapperCol={{ span: 12 }}
							rules={[{ validator: validatormap }]}
							valuePropName="checked"
							name={['content_settings', 'collect', 'systemKeywordStatus']}
						>
							<Checkbox className={s.ml3} disabled={!enable}>
								敏感词
							</Checkbox>
						</Form.Item>
					</div>
					<Form.Item
						className={s.flex1}
						label=""
						labelAlign="left"
						labelCol={{ span: 0 }}
						rules={keyword ? [{ validator: validatormap }] : null}
						wrapperCol={{ span: 24 }}
						name={['content_settings', 'collect', 'systemKeywordTypes']}
					>
						<Select
							option={CONTENT_KEYWORD_TYPES.map(({ idx, label }) => {
								return { label, value: idx };
							})}
							placeholder="请选择敏感词类型"
							disabled={!keyword || !enable}
							className={cn(s.w100p)}
							multiple
							clearable
							searchable
							checkAll
						/>
					</Form.Item>
				</div>
				<div className={cn(s.df, s.aifs)}>
					<div style={{ width: '170px' }}>
						<Form.Item
							labelAlign="left"
							label=""
							labelCol={{ span: 0 }}
							wrapperCol={{ span: 14, offset: 10 }}
							style={{ width: '170px', marginRight: '10px' }}
							valuePropName="checked"
							name={['content_settings', 'collect', 'privacyDisclosureStatus']}
						>
							<Checkbox className={s.ml3} disabled={!enable}>
								隐私信息
							</Checkbox>
						</Form.Item>
					</div>
					<Form.Item
						className={s.flex1}
						label=""
						labelAlign="left"
						labelCol={{ span: 0 }}
						rules={privacy ? [{ validator: validatormap }] : null}
						wrapperCol={{ span: 24, offset: 0 }}
						name={['content_settings', 'collect', 'privacyDisclosureTypes']}
					>
						<Select
							option={CONTENT_PRIVACY_DISCLOSURE_TYPES.map(({ idx, label }) => {
								return { label, value: idx };
							})}
							placeholder="请选择隐私信息类型"
							disabled={!privacy || !enable}
							className={cn(s.w100p)}
							multiple
							clearable
							searchable
							checkAll
						/>
					</Form.Item>
				</div>
				<div
					className={cn(s.pr)}
					style={{ display: contentType === 'assign' ? 'block' : 'none' }}
				>
					<Form.Item
						className={cn(s.mt10)}
						label="指定页面"
						labelAlign="left"
						labelCol={{ span: 2 }}
						rules={
							contentType === 'assign' ? [{ validator: validatormap }] : null
						}
						wrapperCol={{ span: 20 }}
						name={['content_settings', 'collect', 'includeUrl']}
					>
						<Textarea
							disabled={!enable}
							placeholder="请输入监测URL关键参数，一行一个。如您需要监测地址是‘http://www.scanv.com/admin/’, 可在此输入‘/admin/’即可。若仅监测首页，填写‘/’即可。"
							rows="4"
						></Textarea>
					</Form.Item>
				</div>
				<div
					className={cn(s.df, s.aic, s.w450)}
					style={{ display: contentType === 'assign' ? 'none' : 'flex' }}
				>
					<div className={cn(s.flex1, s.pr)}>
						<Form.Item
							label="监测深度"
							labelAlign="left"
							labelCol={{ span: 8 }}
							wrapperCol={{ span: 10 }}
							name={['content_settings', 'collect', 'depth']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2, s.ml_2)}
								option={getMaxDepthOptions('content')}
							/>
						</Form.Item>
					</div>
					<div className={cn(s.flex1, s.pr)}>
						<Form.Item
							label="监测最大URL数"
							labelAlign="left"
							labelCol={{ span: 12 }}
							wrapperCol={{ span: 10 }}
							name={['content_settings', 'collect', 'maxPage']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2)}
								option={getMaxPageOptions('content')}
							/>
						</Form.Item>
					</div>
				</div>
			</div>
		</Form>
	);
}

function ChangeCheckSettings({ data, enable, triggerType, type }) {
	const form = Form.useFormInstance();
	const [itemControl, setItemControl] = useState(enable ? 'down' : 'up');
	const changeCheckType =
		Form.useWatch(['change_check_settings', 'collect', 'type'], form) ||
		data?.change_check_settings?.collect?.type;
	const changeType =
		Form.useWatch(['change_check_settings', 'collect', 'changeType'], form) ||
		data?.change_check_settings?.collect?.changeType;
	const validatormap = (rule, value) => {
		if (type === '上一步') {
			return Promise.resolve();
		}
		return Promise.resolve();
	};
	return (
		<Form
			form={form}
			className={s.settingsItem}
			initialValues={data}
			labelAlign="right"
			labelCol={{ span: 3 }}
			name="changeCheckSettings"
			onValuesChange={(newItem, allValues) => {
				const val = recursion(newItem);
				form.setFieldsValue(val);
			}}
			wrapperCol={{ span: 20, offset: 1 }}
		>
			<div
				className={cn(s.bdb, s.pb10, s.df, s.jcsb, s.aic, 'cp')}
				onClick={() => {
					setItemControl(itemControl === 'up' ? 'down' : 'up');
				}}
			>
				<div>
					<Label className={cn(s.label, s.dib, s.vam)}>
						篡改监测
						{!enable && notEnableTip()}
					</Label>
				</div>
				<Icon type={itemControl} className={cn(s.fs14, s.cp)} />
			</div>
			<div className={cn(s.m20_0, s.w876, s['content-' + itemControl])}>
				<Form.Item
					label="监测方式"
					labelCol={{ span: 2 }}
					labelAlign="left"
					wrapperCol={{ span: 22 }}
					name={['change_check_settings', 'collect', 'type']}
				>
					<Radio.Group>
						<Radio disabled={!enable} value="full" className={cn(s.vam, s.h24)}>
							全量监测
						</Radio>
						<Radio disabled={!enable} className={cn(s.vam, s.h24)} value="part">
							指定页面监测
						</Radio>
					</Radio.Group>
				</Form.Item>
				<div className={cn(s.df, s.aifs)}>
					<div
						style={{ width: '60px', lineHeight: '32px', marginRight: '10px' }}
					>
						监测内容:{' '}
					</div>
					<Form.Item
						className={s.flex1}
						label={
							<div className="df aic pr">
								变更类型
								<Helper
									placement="top"
									overlay={
										<div className={s.maxW300}>
											<div>
												文本变更：当次爬取网页源码信息同样本对比分析，计算变更比例；
											</div>
											<div>
												结构变更：当次爬取网页结构信息同样本对比分析，计算变更比例；
											</div>
											<div>
												资源变更：当次爬取站点资源（图片、JS、CSS等文件）同样本对比分析，计算有变更的资源数占总资源数的比例。
											</div>
										</div>
									}
								/>
							</div>
						}
						labelAlign="right"
						labelCol={{ span: 3 }}
						wrapperCol={{ span: 20 }}
						name={['change_check_settings', 'collect', 'changeType']}
					>
						<Select
							option={[
								{ label: '文本变更', value: 'text' },
								{ label: '结构变更', value: 'structure' },
								{ label: '资源变更', value: 'resource' },
							]}
							className={cn(s.w100p)}
							placeholder="请选择篡改变更类型"
							disabled={!enable}
							multiple
							clearable
							searchable
							checkAll
						/>
					</Form.Item>
				</div>
				<Form.Item
					className={cn(s.ml70)}
					label="重点关注资源"
					labelAlign="right"
					labelCol={{ span: 3 }}
					wrapperCol={{ span: 20 }}
					name={['change_check_settings', 'collect', 'resources']}
				>
					<Textarea
						disabled={
							!enable ||
							(changeType.length === 1 && changeType.includes('resources'))
						}
						placeholder={`请输入重点关注的资源链接，一行一个，多个换行展示，例如\nhttp://10.0.8.202/static/dev/js/jquery.js\nhttp://10.0.8.202/phpwind87/register.css`}
						rows="4"
					></Textarea>
				</Form.Item>
				<Form.Item
					className={cn(s.ml70)}
					label="自定义违规词"
					labelAlign="right"
					labelCol={{ span: 3 }}
					wrapperCol={{ span: 20 }}
					name={['change_check_settings', 'collect', 'keywords']}
				>
					<Textarea
						disabled={!enable}
						placeholder={`请输入自定义违规词，一行一个，每个至多40个字符，多个换行展示，例如\n反动\n博彩`}
						rows="4"
					></Textarea>
				</Form.Item>
				<div
					className={cn(s.pr)}
					style={{ display: changeCheckType === 'part' ? 'block' : 'none' }}
				>
					<Form.Item
						className={cn(s.mt10)}
						label="指定页面"
						labelAlign="left"
						labelCol={{ span: 2 }}
						rules={
							changeCheckType === 'part' ? [{ validator: validatormap }] : null
						}
						wrapperCol={{ span: 20 }}
						name={['change_check_settings', 'collect', 'includeUrl']}
					>
						<Textarea
							disabled={!enable}
							placeholder="请输入监测URL关键参数，一行一个。如您需要监测地址是‘http://www.scanv.com/admin/’, 可在此输入‘/admin/’即可。若仅监测首页，填写‘/’即可。"
							rows="4"
						></Textarea>
					</Form.Item>
				</div>
				<div className={cn(s.df, s.aic, s.w100p)}>
					<div
						className={cn(s.flex1, s.pr)}
						style={{ display: changeCheckType === 'part' ? 'none' : '' }}
					>
						<Form.Item
							label="监测深度"
							labelAlign="left"
							labelCol={{ span: 8 }}
							wrapperCol={{ span: 12 }}
							name={['change_check_settings', 'collect', 'depth']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2, s.ml_2)}
								option={getMaxDepthOptions('changeCheck')}
							/>
						</Form.Item>
					</div>
					<div
						className={cn(s.flex1, s.pr)}
						style={{ display: changeCheckType === 'part' ? 'none' : '' }}
					>
						<Form.Item
							label="监测最大URL数"
							labelAlign="left"
							labelCol={{ span: 12 }}
							wrapperCol={{ span: 10 }}
							name={['change_check_settings', 'collect', 'maxPage']}
						>
							<Select
								disabled={!enable}
								className={cn(s.w100p, s.pr, s.t_2)}
								option={getMaxPageOptions('changeCheck')}
							/>
						</Form.Item>
					</div>
					<div className={cn(s.w450, 'df aic')}>
						<Form.Item
							label=""
							className={s.mt_5}
							labelAlign="left"
							labelCol={{ span: 0 }}
							wrapperCol={{ span: 24 }}
							valuePropName="checked"
							name={['change_check_settings', 'collect', 'enableBaseChange']}
						>
							<Checkbox className={s.ml3} disabled={!enable}>
								自动更新样本频率
								<Helper
									placement="top"
									overlay="系统将按设置的频率自动覆盖更新样本信息，您也可前往“综合管理-篡改策略”手动更新样本。"
								/>
								:
							</Checkbox>
						</Form.Item>
						<div className="df aifs w260 ml10">
							<span className="mt5">每监测</span>
							<Form.Item
								label=""
								labelAlign="left"
								className="w100 pl10 pr10"
								labelCol={{ span: 0 }}
								wrapperCol={{ span: 24 }}
								name={['change_check_settings', 'collect', 'baseChangeCount']}
							>
								<Select
									disabled={!enable}
									className={cn(s.w100p, s.pr, s.t_2)}
									option={getChangeBaseOptions()}
								/>
							</Form.Item>
							<span className="mt5">次，进行一次更新</span>
						</div>
					</div>
				</div>
			</div>
		</Form>
	);
}

function SpiderSettings({ data, enable, triggerType }) {
	const VUL_SETTING_OPTIONS = window.kuiper?.app?.config[name].settingOptions;
	const form = Form.useFormInstance();
	const jobIds = Form.useWatch(['job_ids'], form) || data?.job_ids;
	const [itemControl, setItemControl] = useState(
		jobIds?.length > 1 ? 'up' : 'down'
	);
	const [loginControl, setLoginControl] = useState(
		jobIds?.length > 1 ? 'up' : 'down'
	);
	const [customControl, setCustomControl] = useState(
		jobIds?.length > 1 ? 'up' : 'down'
	);
	const siteLogin =
		Form.useWatch(['prelogin', 'site_login'], form) ||
		data?.prelogin?.site_login;
	const loginMethod =
		Form.useWatch(['prelogin', 'login_method'], form) ||
		data?.prelogin?.login_method;
	const httpEnabled =
		Form.useWatch(['prelogin', 'is_http_auth_enabled'], form) ||
		data?.prelogin?.is_http_auth_enabled;
	const proxyEnabled =
		Form.useWatch(['prelogin', 'is_proxy_enabled'], form) ||
		data?.prelogin?.is_proxy_enabled;

	return (
		<Form
			form={form}
			className={s.settingsItem}
			initialValues={data}
			labelAlign="right"
			labelCol={{ span: 3 }}
			name="spiderSettings"
			onValuesChange={(newItem, allValues) => {
				const val = recursion(newItem);
				form.setFieldsValue(val);
			}}
			wrapperCol={{ span: 20, offset: 1 }}
		>
			<div
				className={cn(s.bdb, s.pb10, s.df, s.jcsb, s.aic, 'cp')}
				onClick={() => {
					setItemControl(itemControl === 'up' ? 'down' : 'up');
				}}
			>
				<div>
					<Label className={cn(s.label, s.dib, s.vam)}>
						爬虫设置
						{jobIds?.length > 1 && (
							<span className={cn(s.warningColor, s.ml10, s.fwn)}>
								高级配置不支持针对多个资产进行批量设置，若您的资产需要进行高级配置，请单独下发监测任务。
							</span>
						)}
					</Label>
				</div>
				<Icon type={itemControl} className={cn(s.fs14, s.cp)} />
			</div>
			<div className={cn(s.m20_0, s.w100p, s['content-' + itemControl])}>
				<div
					onClick={() => {
						setLoginControl(loginControl === 'up' ? 'down' : 'up');
					}}
					className={cn(
						s.subLabel,
						s.borderLrb,
						s.bdt,
						s.brtr,
						s.df,
						s.aic,
						s.jcsb,
						s.cp
					)}
				>
					<div>预登录</div>
					<Icon type={loginControl} className={cn(s.fs12, s.ml10, s.cp)} />
				</div>
				<div
					className={cn(
						s.p20_0,
						s.borderLrb,
						s.bsbb,
						s['content-' + loginControl]
					)}
				>
					<Form.Item
						labelCol={{ span: 3 }}
						wrapperCol={{ span: 21 }}
						label="网站登录"
						name={['prelogin', 'site_login']}
					>
						<Switch
							checkedValue={true}
							unCheckedValue={false}
							disabled={jobIds?.length > 1}
						/>
					</Form.Item>
					<div style={{ display: siteLogin ? 'block' : 'none' }}>
						<Form.Item
							label="登录方式"
							labelCol={{ span: 5 }}
							wrapperCol={{ span: 18 }}
							name={['prelogin', 'login_method']}
						>
							<Radio.Group>
								<Radio className={s.h24} value={'form'}>
									表单登录
								</Radio>
								<Radio className={cn(s.ml24, s.h24)} value={'json'}>
									JSON登录
								</Radio>
								<Radio className={cn(s.ml24, s.h24)} value={'cookie'}>
									Cookie
								</Radio>
								<Radio className={cn(s.ml24, s.h24)} value={'headers'}>
									Headers
								</Radio>
							</Radio.Group>
						</Form.Item>
					</div>

					{siteLogin && ['form', 'json'].includes(loginMethod) && (
						<div>
							<Form.Item
								label="登录URL"
								required
								rules={
									siteLogin
										? [
												{
													required: true,
													message: '请输入登录URL',
												},
										  ]
										: []
								}
								labelCol={{ span: 5 }}
								wrapperCol={{ span: 18 }}
								name={['prelogin', `login_${loginMethod}_action_url`]}
							>
								<Input placeholder="请输入登录URL"></Input>
							</Form.Item>
							<Form.Item
								label="POST认证参数"
								required
								rules={
									siteLogin
										? [
												{
													required: true,
													message: '请输入POST认证参数',
												},
										  ]
										: []
								}
								labelCol={{ span: 5 }}
								wrapperCol={{ span: 18 }}
								name={['prelogin', 'login_form_postdata']}
							>
								{loginMethod === 'json' ? (
									<Textarea
										rows="4"
										placeholder={`{"u":"admin","p":"ABCabc123"}`}
									></Textarea>
								) : (
									<Textarea rows="4" placeholder="请输入认证参数"></Textarea>
								)}
							</Form.Item>
						</div>
					)}
					{siteLogin && ['cookie'].includes(loginMethod) && (
						<div>
							<Form.Item
								label="Cookie"
								required
								rules={
									siteLogin
										? [
												{
													required: true,
													message: '请输入登录Cookie',
												},
										  ]
										: []
								}
								labelCol={{ span: 5 }}
								wrapperCol={{ span: 18 }}
								name={['prelogin', 'request_cookie']}
							>
								<Textarea
									rows="4"
									placeholder="例如：_example=afsdfafwefa180b;_example2=BSDF234DFAS598;"
								></Textarea>
							</Form.Item>
						</div>
					)}
					{siteLogin && ['headers'].includes(loginMethod) && (
						<div>
							<Form.Item
								label="headers"
								required
								rules={
									siteLogin
										? [
												{
													required: true,
													message: '请输入登录headers',
												},
										  ]
										: []
								}
								labelCol={{ span: 5 }}
								wrapperCol={{ span: 18 }}
								name={['prelogin', 'request_http_headers']}
							>
								<Textarea
									rows="4"
									placeholder="每一行输入一组key和value。例如:&#13;&#10;Acceot: */*&#13;&#10;Accept-Encoding: gzip,deflate,br&#13;&#10;Host: localhost:3000"
								></Textarea>
							</Form.Item>
						</div>
					)}
					<Form.Item
						labelCol={{ span: 3 }}
						wrapperCol={{ span: 21 }}
						label="HTTP认证"
						name={['prelogin', 'is_http_auth_enabled']}
					>
						<Switch
							checkedValue={true}
							unCheckedValue={false}
							disabled={jobIds?.length > 1}
						/>
					</Form.Item>
					<div style={{ display: httpEnabled ? 'block' : 'none' }}>
						<div className={s.text}>支持BASIC、Digest</div>
						<Form.Item
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							label="用户名"
							name={['prelogin', 'http_auth_username']}
							required
							rules={
								httpEnabled ? [{ required: true, message: '请输入用户名' }] : []
							}
						>
							<Input placeholder="请输入用户名" />
						</Form.Item>
						<Form.Item
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							label="密码"
							name={['prelogin', 'http_auth_password']}
							required
							rules={
								httpEnabled ? [{ required: true, message: '请输入密码' }] : []
							}
						>
							<Input autocomplete="off" placeholder="请输入密码" />
						</Form.Item>
					</div>
					<Form.Item
						labelCol={{ span: 3 }}
						wrapperCol={{ span: 21 }}
						label="代理服务器"
						name={['prelogin', 'is_proxy_enabled']}
					>
						<Switch
							checkedValue={true}
							unCheckedValue={false}
							disabled={jobIds?.length > 1}
						/>
					</Form.Item>
					<div style={{ display: proxyEnabled ? 'block' : 'none' }}>
						<Form.Item
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							label="协议"
							name={['prelogin', 'proxy_scheme']}
							required
							rules={
								proxyEnabled ? [{ required: true, message: '请输入协议' }] : []
							}
						>
							<Input disabled placeholder="请输入协议" />
						</Form.Item>
						<Form.Item
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							label="IP"
							name={['prelogin', 'proxy_host']}
							required
							rules={
								proxyEnabled ? [{ required: true, message: '请输入IP' }] : []
							}
						>
							<Input placeholder="请输入IP" />
						</Form.Item>
						<Form.Item
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							label="端口"
							name={['prelogin', 'proxy_port']}
							required
							rules={
								proxyEnabled ? [{ required: true, message: '请输入端口' }] : []
							}
						>
							<InputNumber className={s.w100p} placeholder="请输入端口" />
						</Form.Item>
						<Form.Item
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							label="用户名"
							name={['prelogin', 'proxy_username']}
						>
							<Input placeholder="请输入用户名" />
						</Form.Item>
						<Form.Item
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							label="密码"
							name={['prelogin', 'proxy_password']}
						>
							<Input placeholder="请输入密码" />
						</Form.Item>
					</div>
				</div>
				<div
					onClick={() => {
						setCustomControl(customControl === 'up' ? 'down' : 'up');
					}}
					className={cn(s.subLabel, s.borderLrb, s.df, s.aic, s.jcsb, s.cp)}
				>
					<div>自定义监测页面</div>
					<Icon type={customControl} className={cn(s.fs12, s.ml10, s.cp)} />
				</div>
				<div
					className={cn(
						s.p20_0,
						s.mb20,
						s.bdb,
						s.borderLrb,
						s.bdc,
						s.brbl,
						s.bsbb,
						s['content-' + customControl]
					)}
				>
					<div className={cn(s.pr, s.pr20)}>
						<Form.Item
							label="需额外监测页面入口"
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							name={['custom_monitor_page', 'includeUrl']}
						>
							<Textarea
								pro
								rows="4"
								id={s.textareaDis}
								disabled={jobIds?.length > 1}
								placeholder="请输入需额外监测页面入口的关键参数，一行一个。如您需要监测页面入口是‘http://www.scanv.com/admin/’，可在此输入‘/admin/’即可。"
							></Textarea>
						</Form.Item>
					</div>
					<div className={cn(s.pr, s.pr20)}>
						<Form.Item
							label="不需监测页面"
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 18 }}
							name={['custom_monitor_page', 'excludeUrl']}
						>
							<Textarea
								rows="4"
								id={s.textareaDis}
								disabled={jobIds?.length > 1}
								placeholder="请输入不需监测页面的关键参数，一行一个。系统自动过滤监测匹配到参数的页面，如您不需要监测地址是‘http://www.scanv.com/admin/’，可在此输入‘/admin/’即可。"
							></Textarea>
						</Form.Item>
					</div>
				</div>
			</div>
		</Form>
	);
}

function HostSettings({ data, enable, triggerType }) {
	const form = Form.useFormInstance();
	const tcp =
		Form.useWatch(['hostSettings', 'is_tcp_enabled'], form) ||
		data?.hostSettings?.is_tcp_enabled;
	const udp =
		Form.useWatch(['hostSettings', 'is_udp_enabled'], form) ||
		data?.hostSettings?.is_udp_enabled;
	const validatormap = (rule, value) => {
		if (rule.field === 'hostSettings.is_udp_enabled' && !value && !tcp) {
			return Promise.reject('主机安全监测必须开启一类端口扫描');
		}
		if (rule.field === 'hostSettings.is_tcp_enabled' && !value && !udp) {
			return Promise.reject('主机安全监测必须开启一类端口扫描');
		}
		return Promise.resolve();
	};
	const [isShowDesign, setIsShowDesign] = useState(false);
	return (
		<Form
			form={form}
			className={s.settingsItem}
			initialValues={data}
			labelAlign="right"
			labelCol={{ span: 3 }}
			name="hostSettings"
			onValuesChange={(newItem, allValues) => {
				const val = recursion(newItem);
				form.setFieldsValue(val);
				console.log(val, newItem, allValues, form);
				allValues.hostSettings.task_type === 'designated_port'
					? setIsShowDesign(true)
					: setIsShowDesign(false);
			}}
			wrapperCol={{ span: 20, offset: 1 }}
		>
			<div className={cn(s.bdb, s.pb10, s.df, s.jcsb, s.aic, 'cp')}>
				<div>
					<Label className={cn(s.label, s.dib, s.vam)}>主机安全监测</Label>
				</div>
			</div>
			<div className={cn(s.m20_0, s.w876)}>
				{/* <Form.Item
					labelCol={{ span: 3 }}
					wrapperCol={{ span: 21 }}
					label="操作系统识别"
					name={['hostSettings', 'is_detect_os_enabled']}
				>
					<Switch checkedValue={true} unCheckedValue={false} />
				</Form.Item> */}
				<Form.Item
					label="监测内容"
					name={['hostSettings', 'job_ids']}
					// validateStatus={errorData?.type}
					// extra={
					// 	errorData?.message ? (
					// 		<span className="danger-color">请选择漏洞模板</span>
					// 	) : (
					// 		<span></span>
					// 	)
					// }
					// rules={[{ required: true, validator: validatormap }]}
				>
					<Select
						placeholder="请选择漏洞模板"
						className={cn(
							s.w90p,
							s.jobIdSelect,
							'jobIdScheduleSelect'
							// atid && s.disw100p
						)}
						checkAll
						multiple
						searchable
						clearable
						// disabled={atid}
					/>
				</Form.Item>

				<Form.Item label="扫描端口" name={['hostSettings', 'task_type']}>
					<Radio.Group>
						<div className={cn(s.df)}>
							<div className={cn(s.df, s.aic)}>
								<Radio
									className={s.h24}
									value="active_port"
									// disabled={atid || !resD?.feature?.httpTask}
								>
									常用端口
								</Radio>
							</div>
							<div className={cn(s.df, s.aic)}>
								<Radio
									className={cn(s.ml24, s.h24)}
									value="designated_port"
									defaultChecked
									// disabled={atid || !resD?.feature?.pingTask}
								>
									指定端口扫描
								</Radio>
							</div>
						</div>
					</Radio.Group>
				</Form.Item>
				{isShowDesign && (
					<Form.Item name={['hostSettings', 'designated_port']}>
						<Textarea
							style={{ marginLeft: '15%' }}
							rows="4"
							placeholder={`请输入端口号，支持范围8080 - 9000，按空格分割`}
						></Textarea>
					</Form.Item>
				)}

				<Form.Item
					label="TCP扫描"
					rules={[{ validator: validatormap }]}
					name={['hostSettings', 'is_tcp_enabled']}
				>
					<Switch checkedValue={true} unCheckedValue={false} />
				</Form.Item>
				<div style={{ position: 'relative' }}>
					<Form.Item
						style={{ width: '100%' }}
						label="UDP扫描"
						rules={[{ validator: validatormap }]}
						name={['hostSettings', 'is_udp_enabled']}
					>
						<Switch checkedValue={true} unCheckedValue={false} />
					</Form.Item>
					<div
						className={cn(s.hint)}
					>
						UDP端口扫描速度较慢，且结果误差大，在没有强烈需求的情况下建议关闭
					</div>
				</div>
			</div>
		</Form>
	);
}

export {
	VulSettings,
	SslSettings,
	SecuritySettings,
	ContentSettings,
	ChangeCheckSettings,
	SpiderSettings,
	HostSettings,
};
